package org.langke.springboot.prometheusmicrometer;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

@RestController
@Slf4j
public class TestController {

    @Autowired
    private PrometheusCustomMonitor monitor;

    @RequestMapping("/order")
    public String order() throws Exception {
        // 统计下单次数
        monitor.getOrderCount().increment();
        Random random = new Random();
        int amount = random.nextInt(100);
        // 统计金额
        monitor.getAmountSum().record(amount);
        return "下单成功, 金额: " + amount;
    }

    @RequestMapping("/webhook")
    public String webhook(@RequestBody String body) {
        log.info("{}", JSONUtil.parse(body).toStringPretty());
        JSONObject jsonObject = JSONUtil.parseObj(body);
        String title = jsonObject.containsKey("title")?jsonObject.getStr("title"):jsonObject.getStr("ruleName");
        String message = jsonObject.getStr("message");
        String requestBody = "{\n" +
                "     \"msgtype\": \"text\",\n" +
                "     \"text\": {\n" +
                "       \"content\" : \""+title+"\n"+message+"\"\n" +
                "    }\n"+
                "}";
        log.info(requestBody);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=5334b43e-724b-4c8f-8a3c-3e1cc4ec22e5";
        String res = HttpUtil.post(url,requestBody);
        log.info("{}:{}",url,res);
        return "success";
    }
}
